package com.starhub.common.security.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义认证入口点（处理未认证访问的异常）
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        // 1. 设置响应状态码和内容类型
//        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
//        response.setCharacterEncoding("UTF-8");
//
//        // 2. 构建错误响应内容
//        Map<String, Object> errorResponse = new HashMap<>();
//        errorResponse.put("code", HttpServletResponse.SC_UNAUTHORIZED);
//        errorResponse.put("message", resolveErrorMessage(authException));
//        errorResponse.put("path", request.getRequestURI());
//        errorResponse.put("timestamp", System.currentTimeMillis());
//
//        // 3. 序列化并返回JSON响应
//        response.getWriter().write(
//                objectMapper.writeValueAsString(errorResponse)
//        );
    }


    /**
     * 根据异常类型解析错误信息
     */
    private String resolveErrorMessage(AuthenticationException exception) {
        String msg = exception.getMessage();
        // 根据具体异常类型细化错误提示
        if (exception.getCause() instanceof ExpiredJwtException) {
            return "身份凭证已过期，请重新登录 | "+msg ;
        } else if (exception.getCause() instanceof JwtException) {
            return "无效的身份凭证 | "+msg;
        } else if (exception instanceof BadCredentialsException) {
            return "认证信息不完整 | " +msg;
        } else if (exception instanceof InsufficientAuthenticationException) {
            return "请求未携带认证信息 | " +msg;
        }
        return msg;
    }


}
